import React, { useState, useEffect } from "react";

import {
  Button,
  Switch,
  Table,
  Popconfirm,
  Modal,
  Form,
  Input,
  Select,
  message,
} from "antd";
import Draggable from "react-draggable";
import {
  addUser,
  deleteUser,
  updateUserInfor,
  getUser,
  verifyUserName,
  roleInfo,
  updateUserPassword,
} from "../../serve";

import "./order.scss";
const { Option } = Select;

const User = () => {
  const [addform] = Form.useForm();
  // const [resetForm] = Form.useForm();
  const [addvisible, setAddVisible] = useState(false);
  const [resetPw, setResetPw] = useState(false);
  const [addType, setAddType] = useState(false);
  // const [none, setNone] = useState("none");
  const [psLength, setPsLength] = useState(0);

  const [userData, setUserData] = useState([]);
  const [udata, upUData] = useState([]);

  const [confirmLoading, setConfirmLoading] = useState(false);
  const [total, setTotal] = useState(1);
  const [confPsw, setConfPsw] = useState(true);
  const [serchData, setSerchData] = useState({
    page: 1,
    limit: 8,
  });
  const [disabled, setDisabled] = useState(true);
  const [role, setRole] = useState([]);
  let draggleRef = React.createRef();

  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });
  const onStart = (event, uiData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      bounds: {
        left: -targetRect.left + uiData.x,
        right: clientWidth - (targetRect.right - uiData.x),
        top: -targetRect.top + uiData.y,
        bottom: clientHeight - (targetRect.bottom - uiData.y),
      },
    });
  };
  const getusers = (datc) => {
    getUser(datc).then((res) => {
      setUserData(res.data);
      setTotal(res.count);
    });
  };
  useEffect(() => {
    getusers(serchData);
  }, [serchData]);
  useEffect(() => {
    roleInfo().then((res) => res.result_code == 200 && setRole(res.data));
  }, []);
  useEffect(() => {
    if (addvisible) {
      let { user } = addform.getFieldValue();
      return !addType
        ? (setConfPsw(true),
          addform.setFieldsValue({ user: { transactionPassword: "a123456" } }))
        : user.permissions == 10002
        ? setConfPsw(false)
        : setConfPsw(true);
    } else {
      addform.setFieldsValue({ user: "" });
    }
  }, [addvisible]);

  const editu = (record) => {
    upUData(record);
    setAddType(true);
    addform.setFieldsValue({ user: record });
    setAddVisible(true);
  };

  const columns = [
    {
      title: "账户名",
      dataIndex: "username",
    },
    {
      title: "姓名",
      dataIndex: "uName",
    },
    {
      title: "权限",
      dataIndex: "userIdentity",
    },
    {
      title: "状态",
      dataIndex: "",
      render: (item) => {
        return (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="禁用"
            loading={confirmLoading}
            checked={item.accountType}
            onChange={(val) => {
              setConfirmLoading(true);
              updateUserInfor({
                accountType: val,
                userId: item.userId,
              })
                .then((rr) => {
                  rr.result_code == 200 &&
                    setSerchData({
                      ...serchData,
                    });
                  setConfirmLoading(false);
                })
                .catch(() => {
                  message.error("网络错误!");
                  setConfirmLoading(false);
                });
            }}
          />
        );
      },
    },
    {
      title: "操作",
      dataIndex: "",
      render: (record) => {
        return (
          <>
            <Button
              type="primary"
              onClick={() => {
                upUData(record);
                setResetPw(true);
              }}
            >
              重置密码
            </Button>
            <Button type="primary" onClick={() => editu(record)}>
              编辑
            </Button>
            <Button type="primary" danger>
              <Popconfirm
                title="确定删除吗?"
                onConfirm={() => handleDelete(record)}
              >
                <a>删除</a>
              </Popconfirm>
            </Button>
          </>
        );
      },
    },
  ];
  function handleDelete(val) {
    deleteUser({ userId: val.userId }).then((res) => {
      return res.result_code == 200
        ? (message.success("删除成功!"), setSerchData({ ...serchData }))
        : message.warning("删除失败!");
    });
  }

  function formChange(file) {
    if (file[0].name[1] == "permissions") {
      file[0].value == 10002 ? setConfPsw(false) : setConfPsw(true);
    }
  }
  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 16 },
  };
  const validateMessages = {
    required: "${label} 是必填的!",
    types: {
      email: "${label} is not a valid email!",
      number: "${label} is not a valid number!",
    },
    number: {
      range: "${label} must be between ${min} and ${max}",
    },
  };
  const onFinish = (r) => {
    setConfirmLoading(true);
    let user = { ...r.user };
    if (addType) {
      updateUserInfor({
        uName: user.uName,
        userId: udata.userId,
        permissions: user.permissions,
      })
        .then((res) =>
          res.result_code == 200
            ? (() => {
                setAddVisible(false);
                setConfirmLoading(false);
                message.success("修改成功!");
                setSerchData({
                  ...serchData,
                });
              })()
            : (message.warning(res.data), setConfirmLoading(false))
        )
        .catch(() => {
          message.error("网络错误,请稍后重试!");
          setConfirmLoading(false);
        });
    } else {
      console.log(user);
      return user.password.length >= 4
        ? addUser(user)
            .then((res) =>
              res.result_code == 200
                ? (() => {
                    setAddVisible(false);
                    setConfirmLoading(false);
                    setSerchData({
                      ...serchData,
                    });
                  })()
                : (message.warning(res.data), setConfirmLoading(false))
            )
            .catch(() => {
              message.error("网络错误,请稍后重试!");
              setConfirmLoading(false);
            })
        : (message.warning("登录密码最少4位!"), setConfirmLoading(false));
    }
  };

  // const onFinishPw = (r) => {
  //   if (r.newPassword !== r.password) {
  //     setNone("inline-block");
  //   } else {
  //     setNone("none");
  //     Axios.post(
  //       `platform/userBranchManagement/updateUserPassword/?userId=${udata.userId}&password=${r.password}`
  //     ).then((r) =>
  //       r.data.result_code == 200
  //         ? (message.success("密码重置成功!"),
  //           setResetPw(false),
  //           resetForm.setFieldsValue({ password: "", newPassword: "" }))
  //         : null
  //     );
  //   }
  // };
  const handOk = () => {
    updateUserPassword({
      userId: udata.userId,
      transactionPassword: "a123456",
      Password: "a123456",
    }).then((r) =>
      r.result_code == 200
        ? (message.success("密码初始化成功!"), setResetPw(false))
        : null
    );
  };

  return (
    <>
      <Button
        type="primary"
        style={{ marginBottom: "18px" }}
        onClick={() => (setAddVisible(true), setAddType(false))}
      >
        添加用户
      </Button>
      <Table
        columns={columns}
        dataSource={userData}
        rowKey={(record) => record.userId}
        pagination={{
          onChange: (page, limit) => {
            setSerchData({
              ...serchData,
              page,
              limit,
            });
          },

          current: serchData.page,
          position: ["bottomCenter"],
          defaultPageSize: serchData.limit,
          total: total, //总条数
        }}
      />

      <Modal
        title={
          <div
            style={{
              width: "100%",
              cursor: "move",
            }}
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false);
              }
            }}
            onMouseOut={() => {
              setDisabled(true);
            }}
          >
            {addType ? "修改用户信息" : "添加用户"}
          </div>
        }
        visible={addvisible}
        onOk={() => addform.submit()}
        confirmLoading={confirmLoading}
        onCancel={() => setAddVisible(false)}
        modalRender={(modal) => (
          <Draggable
            disabled={disabled}
            bounds={bounds}
            onStart={(event, uiData) => onStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
      >
        <Form
          form={addform}
          {...layout}
          name="nest-messages"
          onFinish={onFinish}
          validateMessages={validateMessages}
          onFieldsChange={formChange}
        >
          <Form.Item
            name={["user", "username"]}
            label="账户名"
            rules={[{ required: true }]}
          >
            <Input
              maxLength={12}
              disabled={addType}
              onBlur={(e) => {
                verifyUserName({ username: e.target.value }).then((res) => {
                  return res.result_code == 500
                    ? (() => {
                        message.error(res.data);
                        addform.setFieldsValue({ user: { username: "" } });
                      })()
                    : "";
                });
              }}
            />
          </Form.Item>
          <Form.Item name={["user", "uName"]} label="姓名">
            <Input maxLength={8} />
          </Form.Item>

          <Form.Item
            name={["user", "permissions"]}
            label="用户权限"
            rules={[{ required: true }]}
          >
            <Select>
              {role.map((item) => {
                return (
                  <Option
                    key={item.roleId}
                    value={item.roleId}
                    disabled={
                      item.roleId == 10002 && localStorage.getItem("role") == 1
                    }
                  >
                    {item.roleName}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item noStyle>
            {!addType ? (
              <>
                <Form.Item
                  name={["user", "accountType"]}
                  rules={[{ required: true }]}
                  label="启用状态"
                  valuePropName="checked"
                >
                  <Switch
                    checkedChildren="启用"
                    unCheckedChildren="禁用"
                    defaultChecked={false}
                  />
                </Form.Item>
                <Form.Item
                  onChange={(e) => {
                    console.log();
                    setPsLength(e.target.value.length);
                  }}
                  validateStatus={
                    psLength < 4
                      ? "error"
                      : psLength > 8
                      ? "success"
                      : "warning"
                  }
                  hasFeedback
                  name={["user", "password"]}
                  label="登录密码"
                  rules={[{ required: true }]}
                >
                  <Input.Password
                    maxLength={12}
                    placeholder="密码最少四位,最多12位!"
                  />
                  {/* <span>密码最少四位,最多12位! -- {psLength}/12</span> */}
                </Form.Item>
                <Form.Item
                  name={["user", "transactionPassword"]}
                  label="管理密码"
                >
                  <Input maxLength={12} disabled={confPsw} />
                </Form.Item>
              </>
            ) : null}
          </Form.Item>
        </Form>
      </Modal>

      {/* 重置密码 */}

      <Modal
        title={
          <div
            style={{
              width: "100%",
              cursor: "move",
            }}
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false);
              }
            }}
            onMouseOut={() => {
              setDisabled(true);
            }}
          >
            重置密码
          </div>
        }
        visible={resetPw}
        onOk={handOk}
        // onOk={() => resetForm.submit()}
        onCancel={() => setResetPw(false)}
        modalRender={(modal) => (
          <Draggable
            disabled={disabled}
            bounds={bounds}
            onStart={(event, uiData) => onStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
      >
        {/* <Form
          name="basic"
          form={resetForm}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 17 }}
          onFinish={onFinishPw}
          autoComplete="off"
        >
          <Form.Item label="账户名">
            <span style={{ fontWeight: "800" }}>{udata.username}</span>
          </Form.Item>
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[{ required: true, message: "请输入新密码!" }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            label="再次确认"
            name="password"
            rules={[{ required: true, message: "请再次输入新密码以确认!" }]}
          >
            <Input.Password />
          </Form.Item>

          <span style={{ color: "red", paddingLeft: "99px", display: none }}>
            两次密码不一致,请重新输入!
          </span>
        </Form> */}
        <p>
          此操作将为用户&nbsp;
          <span style={{ fontWeight: "800" }}>{udata.username}</span>&nbsp;
          的登录密码与管理密码恢复为初始值!
        </p>
        <p>
          初始密码均为: <span style={{ fontWeight: 800 }}>a123456</span>
        </p>
      </Modal>
    </>
  );
};

export default User;
